Page({
  data: {},

  onGetUserInfo: function (e) {
    const userInfo = e.detail.userInfo;
    if (userInfo) {
      wx.login({
        success: res => {
          if (res.code) {
            // 发起网络请求
            console.log(res.code);
            wx.request({
              url: 'http://localhost:8080/gpt/wxlogin',
              method: 'POST',
              data: {
                code: res.code,
                username: userInfo.nickName,
              },
              success: function (response) {
                const data = response.data;
                console.log(data);
                if (data.need) {
                  // 跳转到绑定页面
                  wx.navigateTo({
                    url: './bind?openId=' + data.user.openId
                  });
                } else {
                  wx.showToast({
                    title: '登录成功',
                    icon: 'success'
                  });
                  wx.request({
                    url: 'http://localhost:8080/gpt/login',
                    method: 'post',
                    data: {
                      email: data.user.userEmail,
                      password: data.user.userPassword
                    }
                  })
                  // 返回用户信息和openId
                  console.log('用户信息:', data.user);
                  console.log('openId:', data.user.openId);
                }
              },
              fail: function (error) {
                wx.showToast({
                  title: '请求失败',
                  icon: 'none'
                });
                console.error('请求失败', error);
              }
            });
          } else {
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            });
            console.error('登录失败！' + res.errMsg);
          }
        }
      });
    } else {
      wx.showToast({
        title: '未授权',
        icon: 'none'
      });
    }
  }
});